package com.quzi.kettle.activitise.main;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ActivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.httprequest.AsyncBean;
import com.example.httprequest.AsyncHttpUtilClient;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnPullEventListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.RequestParams;
import com.quzi.kettle.GlobalConfig;
import com.quzi.kettle.MyApplication;
import com.quzi.kettle.R;
import com.quzi.kettle.activitise.BaseActivity;
import com.quzi.kettle.activitise.EasyLink;
import com.quzi.kettle.activitise.ScanQRCode;
import com.quzi.kettle.activitise.process.LoginActivity;
import com.quzi.kettle.api.response.BooleanResponse;
import com.quzi.kettle.api.response.DeviceListResponse;
import com.quzi.kettle.bean.http.KettleDevice;
import com.quzi.kettle.utils.MSharePerference;
import com.quzi.kettle.view.TitleBarHandler;
import com.quzi.kettle.view.TitleBarView;

public class MyKettles extends BaseActivity {

	TitleBarView titleView;
	PullToRefreshListView deviceListView;
	dataListAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_kettles);

		deviceListView = (PullToRefreshListView) findViewById(R.id.devicelist);
		initTitleBar();
		deviceListView
				.setOnPullEventListener(new OnPullEventListener<ListView>() {

					@Override
					public void onPullEvent(
							PullToRefreshBase<ListView> refreshView,
							State state, Mode direction) {
						net_deviceList();
					}
				});

		net_deviceList();

	}

	Handler handler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			adapter = new dataListAdapter(deviceList);
			deviceListView.setAdapter(adapter);
		};
	};

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		adapter = new dataListAdapter(deviceList);
		deviceListView.setAdapter(adapter);
		// com.quzi.kettle.activitise.added.ActivityManager.getInstance()
		// .exitBefore();
	}

	private boolean ifListContainTopic() {
		for (int i = 0; i < deviceList.size(); i++) {
			if (deviceList.get(i).getMain_mac().equals(GlobalConfig.topic)) {
				return true;
			}
		}
		return false;

	}

	public void net_deviceList() {
		// if (!isShowingDialog()) {
		// showLoadingDialog();
		// }
		AsyncHttpUtilClient.request(
				getApplicationContext(),
				new AsyncBean(AsyncHttpUtilClient.GET, MyApplication.url
						+ MyApplication.requestMap
								.get(MyApplication.DEVICE_LIST),
						MyApplication.header, null),
				new DeviceListResponse<List<KettleDevice>>() {

					@Override
					public void onFailure(int arg0, String arg1) {
						// if (isShowingDialog()) {
						// dissLoadingDialog();
						// }

						UIHandler.obtainMessage(TOASTMSG, "刷新列表失败")
								.sendToTarget();
					}

					@Override
					public void onSuccess(List t) {
						// if (isShowingDialog()) {
						// dissLoadingDialog();
						// }

						deviceList.clear();
						deviceList = t;
						if (!ifListContainTopic()) {
							GlobalConfig.topic = "";
						}
						// KettleDevice virtualDevice = new KettleDevice();
						// virtualDevice.setMain_mac("aabbccddeeff");
						// virtualDevice.setName("虚拟水壶");
						// virtualDevice.setOnline(true);
						// deviceList.add(0, virtualDevice);
						Log.d("MyKettlt", "device list = " + deviceList);
						Log.d("MyKettle", "t = " + t);
						handler.sendEmptyMessage(0);
					}
				});

	}

	/**
	 * 点击返回按键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {// 如果按下的是回退健
			// 表示按下回退键且不是常按
			if (event.getAction() == KeyEvent.ACTION_DOWN
					&& event.getRepeatCount() == 0) {
				if (deviceList.size() == 0) {
					MSharePerference.getInstance(getApplicationContext())
							.updateBoolean("isCheck", false);

					nextActivity(LoginActivity.class);
				} else {
					nextActivity(MainActivityTest.class);
				}

				// 调用上面写的退出

				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void initTitleBar() {
		super.initTitleBar();
		titleView = (TitleBarView) findViewById(R.id.titleview);
		titleView.setTitle(getResources().getString(R.string.mykettle));
		titleView.setRightIncon(R.drawable.plus);

		titleView.setTitleBarClickListener(new TitleBarHandler() {

			@Override
			public void ClickRight() {
				// 添加流程
				// nextActivity(ScanQRCode.class);
				nextActivity(EasyLink.class);
			}

			@Override
			public void ClickLeft() {
				if (isShowingDialog()) {
					dissLoadingDialog();
				}
				if (deviceList.size() == 0) {
					MSharePerference.getInstance(getApplicationContext())
							.updateBoolean("isCheck", false);

					nextActivity(LoginActivity.class);
				} else {
					nextActivity(MainActivityTest.class);
				}
			}
		});
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

	}

	class dataListAdapter extends BaseAdapter {
		String[] Detail;
		List<KettleDevice> list;
		int[] imge;

		dataListAdapter() {
			Detail = null;
			imge = null;
		}

		public dataListAdapter(List<KettleDevice> list) {
			this.list = list;
		}

		public void updateData(List<KettleDevice> list) {
			this.list.clear();
			Log.d("MyKettle", "updateList");
			this.list.addAll(list);
			notifyDataSetChanged();
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {

			final LayoutInflater inflater = getLayoutInflater();
			View row;
			row = inflater.inflate(R.layout.device_item, parent, false);
			TextView title;
			ImageView device_img = (ImageView) row
					.findViewById(R.id.device_img);
			if (list.get(position).isOnline()) {
				device_img.setImageResource(R.drawable.fresh_press);
			} else {
				device_img.setImageResource(R.drawable.fresh_press_offline);
			}
			title = (TextView) row.findViewById(R.id.name);
			title.setText(list.get(position).getName());

			row.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					if (list.get(position).isOnline()) {
						setTopic(list.get(position).getMain_mac());
						GlobalConfig.topic = list.get(position).getMain_mac();
						currDevice = list.get(position);
						finish();
					} else {
						UIHandler.obtainMessage(TOASTMSG, "亲，您的水壶不在线哦")
								.sendToTarget();
					}
				}
			});

			// if (position != 0) {
			row.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View arg0) {
					View view = View.inflate(getApplicationContext(),
							R.layout.dialog_delete, null);

					TextView cancel = (TextView) view.findViewById(R.id.cancel);
					TextView conform = (TextView) view
							.findViewById(R.id.confirm);

					cancel.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}
					});

					conform.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							if (!isShowingDialog()) {
								showLoadingDialog();
							}
							Map<String, String> map = new HashMap<String, String>();
							map.put("main_mac", list.get(position)
									.getMain_mac());
							AsyncHttpUtilClient
									.request(
											getApplicationContext(),
											new AsyncBean(
													AsyncHttpUtilClient.POST,
													MyApplication.url
															+ MyApplication.requestMap
																	.get(MyApplication.DEVICE_UNBIND),
													MyApplication.header,
													new RequestParams(map)),
											new BooleanResponse<Boolean>() {

												@Override
												public void onSuccess(Boolean t) {
													// TODO Auto-generated
													// method stub
													dissLoadingDialog();
													dialog.dismiss();
													if (GlobalConfig.topic
															.equals(list
																	.get(position)
																	.getMain_mac())) {
														GlobalConfig.topic = "";
													}

													deviceList.remove(position);

													handler.sendEmptyMessage(0);
													if (t) {
														if (deviceList
																.isEmpty()) {
															// getApplication().exitMultiActivity();
															GlobalConfig.topic = "";

															MSharePerference
																	.getInstance(
																			getApplicationContext())
																	.update(GlobalConfig.MAC,
																			"");

															nextActivity(TempActivity.class);
														} else {
															// net_deviceList();
														}
													}
												}

												@Override
												public void onDataReceived(
														String arg0) {
													// TODO Auto-generated
													// method stub

												}

												@Override
												public void onFailure(int arg0,
														String arg1) {
													// TODO Auto-generated
													// method stub
													dissLoadingDialog();
												}

											});
						}
					});

					showDialog(MyKettles.this, view);
					return false;
				}
			});
			// }
			return (row);
		}
	}

}
